package controllers.manage.order;

import build.OrderBuilder;
import build.OrderItemBuilder;
import com.pingplusplus.model.Charge;
import controllers.BaseController;
import controllers.auth.Secure;
import controllers.auth.SkipAuth;
import enums.GoodsType;
import enums.OrderStatus;
import enums.OrderType;
import enums.PaymentType;
import goods.Goods;
import helper.CSVUtils;
import helper.GenerateQrCodeUtil;
import helper.GlobalConfig;
import helper.PingppHelper;
import jodd.util.StringUtil;
import me.chanjar.weixin.common.util.StringUtils;
import models.AdminSupplier;
import models.admin.AdminUser;
import models.constants.DeletedStatus;
import models.merchant.Colocation;
import models.merchant.Merchant;
import models.venue.coach.Coach;
import models.venue.curriculum.Curriculum;
import models.venue.room.Room;
import models.venue.seat.Seat;
import models.weixin.WebUser;
import models.weixin.amount.RechargeCombo;
import models.weixin.amount.WebUserAccount;
import notice.OrderNotice;
import order.Order;
import order.OrderItem;
import order.OrderSource;
import play.Logger;
import play.db.jpa.JPA;
import play.libs.WS;
import play.modules.paginate.JPAExtPaginator;
import play.mvc.Controller;
import play.mvc.With;
import util.common.ConvertUtil;
import util.common.DateUtil;

import java.io.File;
import java.text.DecimalFormat;
import java.util.*;


/**
 * 订单管理
 * Created by buhaoba on 2017/4/12.
 */
@With(BaseController.class)
public class OrderCtrl extends Controller {


    @SkipAuth
    public static void showcode() {
        render();
    }

    @SkipAuth
    public static void paytype(Long id , PaymentType paymentType) {
        Logger.info("OrderCtrl.paytype");
        Map<String , Object> resultMap = new HashMap<>();
        Order order = Order.findByOrderId(id);
        if(order == null) {
            resultMap.put("success" , false);
            resultMap.put("msg" , "订单不存在或已删除");
        }

        //设置所有的二维码支付取消
        JPA.em().createNativeQuery("update orders set show_code = FALSE ").executeUpdate();

        //设置新的二维码支付
        order.showCode = true;
        order.paymentType = paymentType;
        order.save();



        resultMap.put("success" , true);
        resultMap.put("msg" , "支付二维码生成成功，请客户在小屏幕支付");
        renderJSON(resultMap);
    }


    /**
     * 跳转到订单管理页面
     */
    public static void index(Integer pageNumber,
                             String orderNumber,
                             String startTime,
                             String endTime,
                             OrderStatus status,
                             PaymentType payType,
                             GoodsType orderType ,
                             Long  supplierId ,
                             Boolean frozenGoodsType){

        Merchant merchant = Secure.getLoginUser().merchant;
        List<AdminSupplier> supplierList = AdminSupplier.loadAllSupplier();

        pageNumber = pageNumber == null ? 1 : pageNumber;
        Map<String , Object> searchMap = new HashMap<>();

        if(StringUtil.isNotBlank(orderNumber)) {
            searchMap.put("orderNumber", orderNumber);
        }

        if(StringUtil.isNotBlank(startTime)) {
            searchMap.put("startTime", startTime+" 00:00:00");
        }

        if(StringUtil.isNotBlank(endTime)) {
            searchMap.put("endTime", endTime+" 00:00:00");
        }

        if(status != null) {
            searchMap.put("status", status);
        }

        if(payType != null) {
            searchMap.put("payType", payType);
        }

        if(orderType != null && (frozenGoodsType == null || !frozenGoodsType)) {
            searchMap.put("orderType", orderType);
        }

        if(merchant != null){
            searchMap.put("merchantId", merchant.id);
        }
        if(supplierId != null){
            searchMap.put("supplierId", supplierId);
        }

        if(frozenGoodsType != null && frozenGoodsType) {
            searchMap.put("orderType0", GoodsType.PRODUCT );
            searchMap.put("orderType1", GoodsType.THIRDPARTY );
            searchMap.put("orderType2", GoodsType.NO_PRODUCT);

            flash.put("menuId" , "131");
        } else {
            flash.put("menuId", "17");
        }

        JPAExtPaginator<Order> resultPage = Order.findByCondition(searchMap, "id desc", pageNumber, GlobalConfig.PAGE_SIZE);
        Logger.info("getPageCount : %s" , resultPage.getCurrentPage());
        for(Order o : resultPage.getCurrentPage()) {
            Logger.info("orderNumber:%s" , o.orderNumber);
        }

        render(resultPage, pageNumber, orderNumber, startTime, endTime, status, payType, orderType , frozenGoodsType , supplierList , supplierId);
    }

    /**
     * 跳转到订单明细页面
     */
    public static void detail(long id, Integer pageNumber){
        Order order = Order.findById(id);
        List<OrderItem> orderItems = null;
        if(order != null)
            orderItems = OrderItem.getListByOrder(order);
        render(order, pageNumber, orderItems);
    }

    @SkipAuth
    public static void orderPrint(Long id , Integer pageNumber) {
        Order order = Order.findById(id);
        List<OrderItem> orderItems = null;
        if(order != null)
            orderItems = OrderItem.getListByOrder(order);
        render(order, pageNumber, orderItems);
    }

    /**
     * 确认订单
     */
    public static void confirmOrder(long id){
        Map<String , Object> resultMap = new HashMap<>();
        Order order = Order.findById(id);
        if(order.status == OrderStatus.UNPAID){
            resultMap.put("success" , false);
            resultMap.put("msg" , "订单尚未支付!");
            renderJSON(resultMap);
            return;
        }

        order.confirmStatus="ok";
        order.save();

        resultMap.put("success" , true);
        resultMap.put("msg" , "订单确认成功!");
        renderJSON(resultMap);
    }

    /**
     * 跳转到支付页面
     */
    @SkipAuth
    public static void pay(String orderNumber, String goodsType, String payType){
        Order order = Order.findByOrderNumber(orderNumber);
        render(orderNumber, goodsType, order, payType);
    }

    /**
     * 会员卡支付
     */
    @SkipAuth
    public static void cashPay(String orderNumber, String phone){
        Map<String , Object> resultMap = new HashMap<>();
        Order order = Order.findByOrderNumber(orderNumber);
        WebUser webUser = WebUser.findByPhone(phone);
        if(webUser == null) {
            resultMap.put("success" , false);
            resultMap.put("msg" , "会员信息不存在或已删除");
            renderJSON(resultMap);
        }

        if(order.goodsType == null) {
            resultMap.put("success" , false);
            resultMap.put("msg" , "订单付款类型不存在或未设定");
            renderJSON(resultMap);
        }

        WebUserAccount account = WebUserAccount.findByWebUserAndGoodsType(webUser , order.goodsType);
        if(account == null) {
            resultMap.put("success" , false);
            resultMap.put("msg" , "账户不存在 请扫描前台二维码注册");
            renderJSON(resultMap);
        }

        if(account.amount <= order.amount) {
            resultMap.put("success" , false);
            resultMap.put("msg" , "账户余额不足 请先充值");
            renderJSON(resultMap);
        }


        new OrderNotice(order , webUser ,  "订单:" + order.orderNumber + "待确认付款").save();
        resultMap.put("success" , true);
        resultMap.put("msg" , "订单确认消息发送成功， 等待会员确认");
        renderJSON(resultMap);
    }

    /**
     * 支付宝 先保存手机号
     */
    public static void aliFirst(String orderNumber, String phone){
        Map<String , Object> resultMap = new HashMap<>();
        Order order = Order.findByOrderNumber(orderNumber);
        WebUser webUser = WebUser.findByPhone(phone);
        if(webUser == null) {
            resultMap.put("success" , false);
            resultMap.put("msg" , "会员信息不存在或已删除");
            renderJSON(resultMap);
        }

        if(order.goodsType == null) {
            resultMap.put("success" , false);
            resultMap.put("msg" , "订单付款类型不存在或未设定");
            renderJSON(resultMap);
        }

        order.webUser = webUser;
        order.save();

        resultMap.put("success" , true);
        resultMap.put("msg" , "ok");
        renderJSON(resultMap);
    }



    @SkipAuth
    private static String getOrCode(String codeUrl){
        System.out.println("------获取二维码");
        String filePath = "/public/upload/";// 存储二维码路径
        return GenerateQrCodeUtil.generateQrcode(codeUrl, filePath);
    }

    @SkipAuth
    private static String buildBody(GoodsType goodType, Order order){
        String body = "";
        if(order != null){
            List<OrderItem> orderItems = order.orderItems;
            if(goodType == GoodsType.COACH) {// 私教

                body += "购买了私教->";
                int i = 0;
                for(OrderItem item : orderItems){
                    if(i > 0) body += ",";
                    Coach coach = Coach.findById(item.goods.serialId);
                    String tmp = item.goods.name.split("_")[2];

                    String finalName = tmp.substring(0,4)
                            + "." + tmp.substring(4,6)
                            + "." + tmp.substring(6,8)
                            + " " + tmp.substring(8,10)
                            + ":" + tmp.substring(10,12)
                            + "-" + tmp.substring(12,14)
                            + ":" + tmp.substring(14);
                    body += coach.coachImage +"-"+finalName+"-"+item.salePrice;
                    i ++;
                }

            } else if(goodType == GoodsType.PRODUCT) {// 商品

                body += "购买了商品->";
                int i = 0;
                for(OrderItem item : orderItems){
                    if(i > 0) body += ",";

                    body += item.goods.name +"-"+item.salePrice;
                    i ++;
                }

            } else if(goodType == GoodsType.SPORTS_ROOMS) {// 包房

                body += "订购了包房->";

            }
        }
        return body;
    }


    /**
     * 首页创建订单
     * @param amount
     * @param remark
     */
    @SkipAuth
    public static void indexCreateOrder(Double amount , String remark , Long supplierId) {
        AdminUser adminUser = Secure.getLoginUser();
        if(amount == null || amount == 0 || supplierId == null || supplierId ==0) {
            flash.put("msg" , "填写信息有错误，请检查后重试");
            redirect("/");
        }

        Goods goods = Goods.findOrCreateCASH(amount , GoodsType.CASH);

        AdminSupplier supplier = AdminSupplier.findById(supplierId);
        if(supplier == null) {
            flash.put("msg" , "供应商不存在，请检查后 重试");
            redirect("/");
        }
        OrderBuilder orderBuilder = OrderBuilder.forBuild().type(OrderType.PC).merchant(adminUser.merchant).goodsType(GoodsType.CASH).adminSupplier(supplier);
        Order order = orderBuilder.save();
        //保存操作人信息
        order.createAt = new Date();
        order.creator = adminUser;
        order.ctDept = adminUser.adminDept != null ? adminUser.adminDept : null;
        order.remark = remark;
        order.save();

        // 添加订单内容
            OrderItemBuilder orderItemBuilder = orderBuilder.addGoods(goods);
            orderItemBuilder
                    .amount(goods.salePrice)
                    .salePrice(goods.salePrice);
            orderItemBuilder.build();
        orderBuilder.changeToUnPaid();
        flash.put("msg" , "订单创建成功");
        redirect("/BS0023/admin/order/detail/"+order.id+"/1");
    }



    /**
     * 房间创建现金订单
     * @param amount
     * @param remark
     */
    @SkipAuth
    public static void roomCashOrder(Double amount , String remark , Long roomId) {
        AdminUser adminUser = Secure.getLoginUser();
        if(amount == null || amount == 0 || roomId == null || roomId ==0) {
            flash.put("msg" , "填写信息有错误，请检查后重试");
            redirect("/");
        }

        Goods goods = Goods.findOrCreateCASH(amount , GoodsType.CASH);

        Room room = Room.findById(roomId);
        if(room == null) {
            flash.put("msg" , "房间不存在，请检查后 重试");
            redirect("/");
        }
        OrderBuilder orderBuilder = OrderBuilder.forBuild().type(OrderType.PC).merchant(adminUser.merchant).goodsType(GoodsType.SPORTS_ROOMS).adminSupplier(room.adminSupplier);
        Order order = orderBuilder.save();
        //保存操作人信息
        order.createAt = new Date();
        order.creator = adminUser;
        order.ctDept = adminUser.adminDept != null ? adminUser.adminDept : null;
        order.remark = remark;
        order.save();

        // 添加订单内容
        OrderItemBuilder orderItemBuilder = orderBuilder.addGoods(goods);
        orderItemBuilder
                .amount(goods.salePrice)
                .salePrice(goods.salePrice);
        orderItemBuilder.build();
        orderBuilder.changeToUnPaid();
        flash.put("msg" , "订单创建成功");
        redirect("/BS0023/admin/order/detail/"+order.id+"/1");
    }

    /**
     * 创建订单 教练
     * @param goodsIds
     */
    @SkipAuth
    public static void create(String goodsIds) {
        AdminUser adminUser = Secure.getLoginUser();
        // 生成订单
        OrderBuilder orderBuilder = OrderBuilder.forBuild().type(OrderType.PC).merchant(adminUser.merchant).goodsType(GoodsType.COACH);
        Order order = orderBuilder.save();
        //保存操作人信息
        order.createAt = new Date();
        order.creator = adminUser;
        order.ctDept = adminUser.adminDept != null ? adminUser.adminDept : null;
        order.save();

        // 添加订单内容
        String[] goodsArray = goodsIds.split(",");
        for(String goodsId : goodsArray) {
            if(goodsId == null || "".equals(goodsId)) continue;
            Goods goods = Goods.findById(Long.valueOf(goodsId));
            OrderItemBuilder orderItemBuilder = orderBuilder.addGoods(goods);
            orderItemBuilder
                    .amount(goods.salePrice)
                    .salePrice(goods.salePrice);
            orderItemBuilder.build();
        }
        orderBuilder.changeToUnPaid();
        flash.put("msg" , "订单创建成功");
        redirect("/BS0023/admin/order/detail/"+order.id+"/1");
    }

    /**
     * 创建订单 包房
     * @param webUser
     * @param goodsIds
     */
    @SkipAuth
    public static void createForRoom(WebUser webUser , String goodsIds , AdminSupplier supplier) {
        if(webUser == null) {
            webUser = WebUser.findById(1l);
        }

        AdminUser adminUser = Secure.getLoginUser();

        // 生成订单
        OrderBuilder orderBuilder = OrderBuilder.forBuild().byUser(webUser).type(OrderType.PC).merchant(adminUser.merchant).goodsType(GoodsType.SPORTS_ROOMS);
        Order order = orderBuilder.save();
        //保存操作人信息
        order.createAt = new Date();
        order.creator = adminUser;
        order.ctDept = adminUser.adminDept != null ? adminUser.adminDept : null;
        order.supplier = supplier != null ? supplier : null ;
        order.save();

        // 添加订单内容
        String[] goodsArray = goodsIds.split(",");
        for(String goodsId : goodsArray) {
            if(goodsId == null || "".equals(goodsId)) continue;

            Goods goods = Goods.findById(Long.valueOf(goodsId));
            OrderItemBuilder orderItemBuilder = orderBuilder.addGoods(goods);
            orderItemBuilder
                    .amount(goods.salePrice)
                    .salePrice(goods.salePrice);
            orderItemBuilder.build();
        }

        orderBuilder.changeToUnPaid();
        flash.put("msg" , "订单创建成功");
        redirect("/BS0023/admin/order/detail/"+order.id+"/1");
    }

    /**
     * 创建订单 充值
     * @param webUserId
     * @param rechargeAmountId
     */
    public static void createForUser(long  webUserId , long rechargeAmountId) {
        WebUser webUser = WebUser.findByUserId(webUserId);
        DecimalFormat df = new DecimalFormat("#0.00");
        Map<String,Object> resultMap = new HashMap<>();

        if(webUser == null) {
            resultMap.put("success",false);
            resultMap.put("msg","获取不到会员信息!");
            renderJSON(resultMap);
        }

        RechargeCombo rechargeCombo = RechargeCombo.findById(rechargeAmountId);
        if(rechargeCombo == null) {
            resultMap.put("success",false);
            resultMap.put("msg","套餐信息不存在或已删除!");
            renderJSON(resultMap);
        }
        AdminUser adminUser = Secure.getLoginUser();

        // 生成订单
        OrderBuilder orderBuilder = OrderBuilder.forBuild().byUser(webUser).type(OrderType.PC).merchant(adminUser.merchant).goodsType(GoodsType.RECHARGE);
        Order order = orderBuilder.save();

        //保存操作人信息
        order.createAt = new Date();
        order.creator = adminUser;
        order.ctDept = adminUser.adminDept != null ? adminUser.adminDept : null;
        if(rechargeCombo.giveAmount != null && rechargeCombo.giveAmount >0){

            order.discountRate = ConvertUtil.toDouble(df.format(rechargeCombo.rechargeAmount / (rechargeCombo.rechargeAmount + rechargeCombo.giveAmount)));
        }
        order.save();

        Goods goods = Goods.createRechargeCombo(GoodsType.RECHARGE , rechargeCombo);
        // 添加订单内容
        OrderItemBuilder orderItemBuilder = orderBuilder.addGoods(goods);
        orderItemBuilder
                .amount(goods.salePrice)
                .salePrice(goods.salePrice);
        orderItemBuilder.build();
        orderBuilder.changeToUnPaid();
        order.goodsType =goods.type;
        order.save();
        resultMap.put("success",true);
        resultMap.put("orderId",order.id);
        renderJSON(resultMap);

    }

    /**
     * 创建订单 课程
     * @param id
     */
    public static void createForCurriculum(Long id) {
        AdminUser adminUser = Secure.getLoginUser();

        // 生成订单
        OrderBuilder orderBuilder = OrderBuilder.forBuild().type(OrderType.PC).merchant(adminUser.merchant).goodsType(GoodsType.CURRICULUM);
        Order order = orderBuilder.save();

        Curriculum curriculum = Curriculum.findById(id);
        Goods goods = Goods.createTypeTimeGoodsForCurriculm(GoodsType.CURRICULUM , curriculum);
        //保存操作人信息
        order.createAt = new Date();
        order.creator = adminUser;
        order.ctDept = adminUser.adminDept != null ? adminUser.adminDept : null;
        order.supplier = curriculum.adminSupplier != null ? curriculum.adminSupplier : null ;
        order.save();

        // 添加订单内容
        OrderItemBuilder orderItemBuilder = orderBuilder.addGoods(goods);
        orderItemBuilder
                .amount(goods.salePrice)
                .salePrice(goods.salePrice);
        orderItemBuilder.build();
        orderBuilder.changeToUnPaid();
        flash.put("msg" , "订单创建成功");
        redirect("/BS0023/admin/order/detail/"+order.id+"/1");
    }

    //生成餐饮订单
    public static void createForSeat(long id , Double amount  , String thirdPartyNumber ){
        Logger.info("LOGGER 2017061200001 createForSeat ----------------ID:%s | amount : %s " ,id , amount );
        AdminUser adminUser = Secure.getLoginUser();
        Map<String,Object>  resultMap = new HashMap<>();
        Seat seat = Seat.findBySeatId(id);


        // 生成订单
        OrderBuilder orderBuilder = OrderBuilder.forBuild().type(OrderType.PC).merchant(adminUser.merchant).goodsType(GoodsType.NO_PRODUCT).amount(amount);
        Order order = orderBuilder.save();

        //保存操作人信息
        order.createAt = new Date();
        order.creator = adminUser;
        order.ctDept = adminUser.adminDept != null ? adminUser.adminDept : null;
        order.thirdPartyNumber =StringUtils.isNotBlank(thirdPartyNumber) ? thirdPartyNumber : null;

        order.supplier = seat.adminSupplier != null ?seat.adminSupplier : null ;

        order.save();

        if(seat == null){
            resultMap.put("success",false);
            resultMap.put("msg","桌位不存在,无法生成订单");
            renderJSON(resultMap);
        }
        Goods goods = Goods.createSeatGoods(GoodsType.NO_PRODUCT,seat , amount );

        OrderItemBuilder orderItemBuilder = orderBuilder.addGoods(goods);
        orderItemBuilder.amount(goods.salePrice);
        orderItemBuilder.salePrice(goods.salePrice);
        orderItemBuilder.build();

        orderBuilder.changeToUnPaid();

        resultMap.put("success",true);
        resultMap.put("orderId",order.id);
        renderJSON(resultMap);

    }


    //生成第三方平台订单
    public static void createForThirdParty(long id , Double amount , String thirdOrderNo ){
        Logger.info("LOGGER 2017061200002 createForThirdParty ----------------ID:%s | amount : %s |  thirdOrderNo : %s" ,id , amount  , thirdOrderNo);
        AdminUser adminUser = Secure.getLoginUser();
        Map<String,Object>  resultMap = new HashMap<>();

        // 生成订单
        OrderBuilder orderBuilder = OrderBuilder.forBuild().type(OrderType.PC).merchant(adminUser.merchant).goodsType(GoodsType.THIRDPARTY).amount(amount);
        Order order = orderBuilder.save();

        //保存操作人信息
        order.createAt = new Date();
        order.creator = adminUser;
        order.ctDept = adminUser.adminDept != null ? adminUser.adminDept : null;

        OrderSource orderSource = OrderSource.findById(id);
        if (orderSource == null) {
            resultMap.put("success", false);
            resultMap.put("msg", "第三方平台数据不存在,无法生成订单!");
            renderJSON(resultMap);
        }
        order.orderSource = orderSource;
        order.thirdPartyNumber = thirdOrderNo;
        //第三方平台的订单是已付款状态
        order.status = OrderStatus.PAID;
        order.save();
        Goods goods = Goods.createThirdPartytGoods(GoodsType.NO_PRODUCT,orderSource ,thirdOrderNo, amount);

        OrderItemBuilder orderItemBuilder = orderBuilder.addGoods(goods);
        orderItemBuilder.amount(goods.salePrice);
        orderItemBuilder.salePrice(goods.salePrice);
        orderItemBuilder.build();

//        orderBuilder.changeToUnPaid();
        resultMap.put("success",true);
        resultMap.put("orderId",order.id);
        renderJSON(resultMap);

    }


    //生成租赁订单
    public static void createForColocation(long id){
        Map<String , Object> resultMap = new HashMap<>();
        Colocation colocation = Colocation.findByColocationId(id);
        if(colocation == null){
            resultMap.put("success" , false);
            resultMap.put("msg" , "租赁信息不存在,操作失败!");
            renderJSON(resultMap);
        }
        if(colocation.price == null ){
            resultMap.put("success" , false);
            resultMap.put("msg" , "租赁价格不能为空,操作失败!");
            renderJSON(resultMap);
        }
        AdminUser loginUser = Secure.getLoginUser();

        // 生成订单
        OrderBuilder orderBuilder = OrderBuilder.forBuild().type(OrderType.PC).merchant(loginUser.merchant).goodsType(GoodsType.FEIYANGXINGQIU).amount(colocation.price);
        Order order = orderBuilder.save();

        //保存操作人信息
        order.createAt = new Date();
        order.creator = loginUser;
        order.ctDept = loginUser.adminDept != null ? loginUser.adminDept : null;
        order.save();

        Goods goods = Goods.createColocationGoods(GoodsType.FEIYANGXINGQIU,colocation);

        OrderItemBuilder orderItemBuilder = orderBuilder.addGoods(goods);
        orderItemBuilder.amount(goods.salePrice);
        orderItemBuilder.salePrice(goods.salePrice);
        orderItemBuilder.build();

        orderBuilder.changeToUnPaid();
        colocation.createOrder = true;
        colocation.save();
        resultMap.put("success",true);
        resultMap.put("orderId",order.id);
        renderJSON(resultMap);

    }

    /**
     * 删除订单
     */
    public static void delete(long id , String remark){
        Map<String , Object> resultMap = new HashMap<>();
//        Order order = Order.findById(id);
        Order order = Order.findByOrderId(id);
        if(order == null){
            resultMap.put("success",true);
            resultMap.put("msg","订单不存在,可能已经被删除!");
            renderJSON(resultMap);
        }
        if(StringUtils.isBlank(remark)){
            resultMap.put("success",true);
            resultMap.put("msg","备注不能为空!");
            renderJSON(resultMap);
        }


        // 删除订单子项
        List<OrderItem> orderItems = OrderItem.getListByOrder(order);
        for(OrderItem item : orderItems){
            item.deleted = DeletedStatus.DELETED;
            item.save();
        }

        // 删除订单
        order.deleted = DeletedStatus.DELETED;
        order.remark = remark ;
        order.save();

        flash.put("msg" , "订单删除成功");
//        redirect("/BS0017/admin/order/index/"+pageNumber);
        resultMap.put("success",true);
        renderJSON(resultMap);
    }

    @SkipAuth
    private static String post(String url, String postData) {
        Logger.info("post(url: %s) with body:\n%s", url, postData);
        WS.HttpResponse response = WS.url(url).body(postData).post();
        String responseBody = response.getString("UTF-8");
        Logger.info("   response=" + responseBody);
        return responseBody;
    }

    public static void countPaidUnConfirm(){
        Map<String , Object> resultMap = new HashMap<>();

        Merchant merchant = Secure.getLoginUser().merchant;

//        // ------测试
//        if(merchant == null) merchant = Merchant.findById(1l);

        List<Order> orders = Order.countPaidUnConfirm(merchant.id);
        
        String items = "[";
        int i = 0;
        for(Order order : orders){
            Date orderTime = order.createdAt;
            if(i > 0) items += ",";
            items += "{\"orderTime\":\""+DateUtil.dateToString(orderTime, "MM月dd日 HH:mm")+"\"";
            items += ",\"orderTime2\":\""+DateUtil.dateToString(orderTime, "yyyy年MM月dd日")+"\"";
            items += ",\"webuser\":\""+order.webUser == null ? "未登记姓名" : order.webUser.nickName+"\"";
            items += ",\"id\":\""+order.id+"\"";

            String orderContent = "";
            if(order.goodsType == GoodsType.PRODUCT){
                orderContent = "购买了产品";
            }else if(order.goodsType == GoodsType.COACH){
                orderContent = "预约了私教";
            }else if(order.goodsType == GoodsType.CURRICULUM){
                orderContent = "购买了课程";
            }else if(order.goodsType == GoodsType.SPORTS_ROOMS){
                orderContent = "预定了包房";
            }else if(order.goodsType == GoodsType.RECHARGE){
                orderContent = "进行会员卡充值";
            }
            items += ",\"orderContent\":\""+orderContent+"\"}";
            i ++;
        }
        items += "]";

        resultMap.put("success" , true);
        resultMap.put("msg" , orders.size());
        resultMap.put("items" , items);
        renderJSON(resultMap);
    }

    //导出
    public static void exportExcel(String orderNumber,
                                   String startTime,
                                   String endTime,
                                   OrderStatus status,
                                   PaymentType payType,
                                   GoodsType orderType ,
                                   Boolean frozenGoodsType){

        Merchant merchant = Secure.getLoginUser().merchant;

        Map<String , Object> searchMap = new HashMap<>();

        if(StringUtil.isNotBlank(orderNumber)) {
            searchMap.put("orderNumber", orderNumber);
        }

        if(StringUtil.isNotBlank(startTime)) {
            searchMap.put("startTime", startTime+" 00:00:00");
        }

        if(StringUtil.isNotBlank(endTime)) {
            searchMap.put("endTime", endTime+" 00:00:00");
        }

        if(status != null) {
            searchMap.put("status", status);
        }

        if(payType != null) {
            searchMap.put("payType", payType);
        }

        if(orderType != null && (frozenGoodsType == null || !frozenGoodsType)) {
            searchMap.put("orderType", orderType);
        }

        if(merchant != null){
            searchMap.put("merchantId", merchant.id);
        }

        if(frozenGoodsType != null && frozenGoodsType) {
            searchMap.put("orderType0", GoodsType.PRODUCT );
            searchMap.put("orderType1", GoodsType.THIRDPARTY );
            searchMap.put("orderType2", GoodsType.NO_PRODUCT);

        }

        JPAExtPaginator<Order> resultPage = Order.findByCondition(searchMap, "id desc", null, null);
//        Logger.info("getPageCount : %s" , resultPage.getCurrentPage());

        //标题
        LinkedHashMap<String,String> headerMap = new LinkedHashMap<>();
        headerMap.put("orderNumber","订单编号");
        headerMap.put("nickName","下单人");
        headerMap.put("createdAt","下单时间");
        headerMap.put("goodsTypeStr","类型");
        headerMap.put("amount","金额");
        headerMap.put("orderStatusStr","支付状态");
        headerMap.put("confirmStatus","确认支付");

        //数据列表
        List<Map> dataList = new ArrayList<>();
        DecimalFormat b = new DecimalFormat("#.00");
        if(resultPage != null){
            for(Order order : resultPage){
                Logger.info("orderNumber:%s" , order.orderNumber);
                Map<String,Object> row = new LinkedHashMap<>();
                row.put("orderNumber",order.orderNumber);
                row.put("nickName",order.webUser != null ? order.webUser.nickName : " ");
                row.put("createdAt",DateUtil.dateToString(order.createdAt , "yyyy-MM-dd HH:mm:ss"));
                row.put("goodsTypeStr",GoodsType.getGoodsType(order.goodsType));
                row.put("amount",b.format(order.amount));
                row.put("orderStatusStr",OrderStatus.getOrderStatus(order.status));
                row.put("confirmStatus",order.confirmStatus == null ? "未确认": "已确认");
                dataList.add(row);

            }
        }

        File file = CSVUtils.createCSVFile(dataList , headerMap , "订单列表");
        renderBinary(file);

    }

    //确认发票已开
    public static void confirmInvoice(long orderId , String invoiceCode){
        Order order = Order.findById(orderId);
        Map<String , Object> resultMap = new HashMap<>();

        if(order == null){
            resultMap.put("success",false);
            resultMap.put("msg","订单不存在,可能被删除了!");
            renderJSON(resultMap);
        }


        if(StringUtils.isBlank(invoiceCode)){
            resultMap.put("success",false);
            resultMap.put("msg","发票编号为空 , 操作失败!");
            renderJSON(resultMap);
        }


        //如果订单未付款,则不可执行
        if(order.status != OrderStatus.PAID){
            resultMap.put("success",false);
            resultMap.put("msg","订单未付款,操作失败!!");
            renderJSON(resultMap);
        }

        order.invoiceCode = invoiceCode ;
        order.invoiceStatus = Boolean.TRUE ;
        order.save();

        flash.put("msg","确认成功!");
        resultMap.put("success",true);
        renderJSON(resultMap);

    }
}
